package com.liqi.quartz.task;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.liqi.common.utils.Base64ToMultipartFile;
import com.liqi.common.utils.DateUtils;
import com.liqi.common.utils.minio.MinIoUtils;
import com.liqi.info.domain.TInfoFwzx;
import com.liqi.info.mapper.TInfoFwzxMapper;
import com.liqi.info.service.ITInfoFwzxService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

@Component("EvaluteTask")
public class EvaluteTask {
    private static final Logger logger = LoggerFactory.getLogger(EvaluteTask.class);
    @Value("${Fwzx.picUrl}")
    private String picurl;
    @Value("${Fwzx.url}")
    private String url;
    @Value("${Fwzx.appId}")
    private String appId;
    @Value("${Fwzx.appSecret}")
    private String appSecret;
    @Autowired
    private ITInfoFwzxService itInfoFwzxService;
    @Autowired
    private TInfoFwzxMapper tInfoFwzxMapper;
    @Autowired(required = false)
    private MinIoUtils minIoService;


    private static String urlpic = "http://10.19.131.58:8159";

    // 获取签名
    private String sign(String timestamp, String nonce) {
        String text = appId + "-" + appSecret + "-" + timestamp + "-" + nonce;
        return SmUtil.sm3(text).toLowerCase();
    }

    public void getEvalute() {
        try {
            logger.info("进入方法getEvalute");
            Date date = DateUtil.date();
            String year = String.valueOf(DateUtil.year(date));
            String month = String.valueOf(DateUtil.month(date) + 1);
            HttpRequest request = HttpUtil.createPost(url);
            String timestamp = System.currentTimeMillis() + "";
            String nonce = UUID.randomUUID().toString().replace("-", "");
            String signature = this.sign(timestamp, nonce);
            request.header("X-AppId", appId);
            request.header("X-Timestamp", timestamp);
            request.header("X-Nonce", nonce);
            request.header("X-Signature", signature);
            logger.info("signature加密内容:{}", signature);
            logger.info("HttpRequest内容:{}", request);
            Map<String, Object> map = new HashMap<>();
            map.put("appId", appId);
            map.put("token", "462387BC2FDB488EBAF82C0245CB13D4");
            map.put("Service", "QueueCity.GetHonorList");
            map.put("Type", "月度考核");
            map.put("Title", "服务之星");
            map.put("Year", year);
            map.put("Month", month);
            logger.info("json内容:{}", map);
            request.body(JSON.toJSONString(map));
            // 发起请求
            HttpResponse response = request.execute();
            logger.info("响应内容:{}", response.body());
            String object = com.alibaba.fastjson2.JSONObject.parseObject(response.body(),String.class);
            logger.info("object响应内容:{}", object);
            JSONArray honors = JSONUtil.parseObj(object).getJSONArray("Honors");
            Date dateTime = DateUtil.parse(DateUtils.getTime());
            for (int i = 0; i < honors.size(); i++) {
                JSONArray index = honors.getJSONObject(i).getJSONArray("ItemList");
                for (int j = 0; j < index.size(); j++) {
                    QueryWrapper<TInfoFwzx> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("name", index.getJSONObject(j).getStr("Title_Other"));
                    queryWrapper.eq("deptName", index.getJSONObject(j).getStr("Title"));
                    queryWrapper.eq("branch_code", "22");
                    queryWrapper.eq("t_year", year);
                    queryWrapper.eq("t_month", month);
                queryWrapper.eq("image_path", index.getJSONObject(j).getStr("ImagePath"));
                    //查询是否存在，不存在则添加记录
                    TInfoFwzx tInfoFwzx1 = tInfoFwzxMapper.selectOne(queryWrapper);
                    if (tInfoFwzx1 == null) {
                        TInfoFwzx fwzx = getTInfoFwzx(index.getJSONObject(j), month, year, dateTime);
                        logger.info("插入实体是:{}", fwzx);
                        int i1 = itInfoFwzxService.insertTInfoFwzx(fwzx);
                        logger.info("插入内容条数:{}", i1);
                    } else {
                        //查询图片是否有过修改 有修改则上传文件服务器，并修改当条记录
                        QueryWrapper<TInfoFwzx> wrapper = new QueryWrapper<>();
                        wrapper.eq("image_path", index.getJSONObject(j).getStr("ImagePath"));
                        TInfoFwzx tInfoFwzxImg = tInfoFwzxMapper.selectOne(wrapper);
                        if (tInfoFwzxImg == null) {
                            logger.info("修改base64图片为:{}", index.getJSONObject(j).getStr("ImageBase"));
                            StringBuilder base = new StringBuilder(index.getJSONObject(j).getStr("ImageBase"));
                            String[] base64Array = base.toString().split(",");
                            String dataUir = base64Array[0];
                            String data = base64Array[1];
                            MultipartFile multipartFile = new Base64ToMultipartFile(data, dataUir);
                            String upload = minIoService.upload(multipartFile);
                            tInfoFwzx1.setPic(upload);
                            tInfoFwzx1.setDescription(index.getJSONObject(j).getStr("Content"));
                            tInfoFwzx1.setImagePath(index.getJSONObject(j).getStr("ImagePath"));
                            int i1 = itInfoFwzxService.updateTInfoFwzx(tInfoFwzx1);
                            logger.info("修改内容条数:{}", i1);
                        }else {
                            int i1 = itInfoFwzxService.updateTInfoFwzx(tInfoFwzx1);
                        }
                        // String imageURL = picurl + index.getJSONObject(j).getStr("ImagePath");
                    }

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    private TInfoFwzx getTInfoFwzx(JSONObject jsonObject, String month, String year, Date dateTime) {
        TInfoFwzx tInfoFwzx = new TInfoFwzx();
        logger.info("拼接参数响应内容:{}", tInfoFwzx);
        tInfoFwzx.setTMonth(month);
        tInfoFwzx.setTYear(year);
        tInfoFwzx.setBranchCode("22");
        tInfoFwzx.setName(jsonObject.getStr("Title_Other"));
        tInfoFwzx.setDescription(jsonObject.getStr("Content"));
        logger.info("新增base64图片为:{}", jsonObject.getStr("ImageBase"));
        StringBuilder base = new StringBuilder(jsonObject.getStr("ImageBase"));
        String[] base64Array = base.toString().split(",");
        String dataUir = base64Array[0];
        String data = base64Array[1];
        MultipartFile multipartFile = new Base64ToMultipartFile(data, dataUir);
        String upload = minIoService.upload(multipartFile);
        tInfoFwzx.setPic(upload);
        tInfoFwzx.setImagePath(jsonObject.getStr("ImagePath"));
        tInfoFwzx.setDeptId(jsonObject.getStr("deptId"));
        tInfoFwzx.setDeptname(jsonObject.getStr("Title"));
        tInfoFwzx.setCreateTime(dateTime);
        tInfoFwzx.setUpdateTime(dateTime);
        tInfoFwzx.setStatus(0);
        tInfoFwzx.setCreateBy("admin");
//        MultipartFile multipartFile = new Base64ToMultipartFile(data, dataUir);
//        String upload = minIoService.upload(multipartFile);
        return tInfoFwzx;
    }

    public static void main(String[] args) {
        String json = "{\n" +
                "    \"Honors\": [\n" +
                "        {\n" +
                "            \"Status\": \"1\",\n" +
                "            \"Month\": \"12\",\n" +
                "            \"Type\": \"月度考核\",\n" +
                "            \"Year\": \"2022\",\n" +
                "            \"TitleType\": \"4\",\n" +
                "            \"ItemList\": [\n" +
                "                {\n" +
                "                    \"deptName\": \"黑龙江省政务服务中心\",\n" +
                "                    \"Title_Other\": \"税务局\",\n" +
                "                    \"Content\": \"评价分：9.5\",\n" +
                "                    \"ImagePath\": \"/web/file/download/upload/public/2022/12/10/202212101539020_C.png\",\n" +
                "                    \"deptId\": \"230000036\",\n" +
                "                    \"Title\": \"李美丽\",\n" +
                "                },\n" +
                "                {\n" +
                "                    \"deptName\": \"黑龙江省政务服务中心\",\n" +
                "                    \"Title_Other\": \"民政局\",\n" +
                "                    \"Content\": \"评价分：10\",\n" +
                "                    \"ImagePath\": \"/web/file/download/upload/public/2022/12/10/202212101537013_B.png\",\n" +
                "                    \"deptId\": \"230000036\",\n" +
                "                    \"Title\": \"王美丽\",\n" +
                "                },\n" +
                "                {\n" +
                "                    \"deptName\": \"黑龙江省政务服务中心\",\n" +
                "                    \"Title_Other\": \"公安局\",\n" +
                "                    \"Content\": \"评价分：9.5\",\n" +
                "                    \"ImagePath\": \"/web/file/download/upload/public/2022/12/10/202212101538036_A.png\",\n" +
                "                    \"deptId\": \"230000036\",\n" +
                "                    \"Title\": \"张美丽\",\n" +
                "                }\n" +
                "            ],\n" +
                "            \"Title\": \"服务之星\",\n" +
                "            \"Sort\": \"1\",\n" +
                "            \"Creata_time\": \"\",\n" +
                "            \"Remark\": \"\"\n" +
                "        }\n" +
                "    ],\n" +
                "    \"Succ\": 1\n" +
                "}";

        JSONArray honors = JSONUtil.parseObj(json).getJSONArray("Honors");
        Date date = DateUtil.date();
        String year = String.valueOf(DateUtil.year(date));
        String month = String.valueOf(DateUtil.month(date) + 1);
        List<TInfoFwzx> list = new ArrayList<>();
        for (int i = 0; i < honors.size(); i++) {
            JSONArray index = honors.getJSONObject(i).getJSONArray("ItemList");
            for (int j = 0; j < index.size(); j++) {
                TInfoFwzx tInfoFwzx = new TInfoFwzx();
                String imageURL = urlpic + index.getJSONObject(j).getStr("ImagePath");
                tInfoFwzx.setTMonth(month);
                tInfoFwzx.setTYear(year);
                tInfoFwzx.setBranchCode("22");
                tInfoFwzx.setName(index.getJSONObject(j).getStr("Title_Other"));
                tInfoFwzx.setDescription(index.getJSONObject(j).getStr("Content"));
                tInfoFwzx.setPic(imageURL);
                tInfoFwzx.setDeptId(index.getJSONObject(j).getStr("deptId"));
                tInfoFwzx.setDeptname(index.getJSONObject(j).getStr("Title"));
                Date date1 = DateUtil.parse(DateUtils.getTime());
                tInfoFwzx.setCreateTime(date1);
                tInfoFwzx.setUpdateTime(date1);
                StringBuilder base = new StringBuilder(index.getJSONObject(j).getStr("ImageBase"));
                final String[] base64Array = base.toString().split(",");
                String dataUir = base64Array[0];
                String data = base64Array[1];
                System.out.println(DateUtil.parse(DateUtils.getTime()));
                list.add(tInfoFwzx);
            }

        }

        System.out.println("11111");
    }
}



